package com.zsc.wxm.ysh.anjo.utils;


import cn.hutool.core.date.DateUtil;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jws;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import javax.crypto.spec.SecretKeySpec;
import javax.xml.bind.DatatypeConverter;
import java.security.Key;
import java.util.Date;

/**
 * 描述：jwt生成token
 *
 * @author playmaker
 * @since 2021/1/31 17:53
 */
@Slf4j
public class JwtUtil {
    /**
     * 加密密钥
     */
    private static final String WEB_SECRET = "wxmyshanjoweb";

    /**
     * 过期时间
     */
    private static final long EXPIRE_TIME = 60 * 60 * 1000;

    /**
     * 密钥加密
     */
    private static Key getKeyInstance() {
        SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;
        byte[] bytes = DatatypeConverter.parseBase64Binary(WEB_SECRET);
        return new SecretKeySpec(bytes, signatureAlgorithm.getJcaName());
    }

    /**
     * 生产令牌
     */
    public static String getJwtToken(String phone) {
        return Jwts.builder()
                .setHeaderParam("type", "JWT")
                .setHeaderParam("alg", "HS256")
                //主题
                .setSubject("user-info")
                .setIssuedAt(new Date())
                .setExpiration(DateUtil.date(System.currentTimeMillis() + EXPIRE_TIME))
                .claim("phone", phone)
                .signWith(SignatureAlgorithm.HS256, getKeyInstance())
                .compact();
    }

    /**
     * 判断token是否存在与有效
     *
     * @param jwtToken token
     * @return boolean
     */
    private static boolean checkJwtToken(String jwtToken) {
        if (StringUtils.isEmpty(jwtToken)) {
            return false;
        }
        try {
            Jwts.parser().setSigningKey(getKeyInstance()).parseClaimsJws(jwtToken);
        } catch (Exception e) {
            log.error("token 校验异常,异常信息：{},参数：{}", e.getMessage(), jwtToken);
            return false;
        }
        return true;
    }

    /**
     * 从token获取信息
     *
     * @param token token
     * @return phone
     */
    public static String getUserPhoneByToken(String token) {
        if (!checkJwtToken(token)) {
            return null;
        }
        //解析token
        Jws<Claims> claimsJws = Jwts.parser().setSigningKey(getKeyInstance()).parseClaimsJws(token);
        Claims claims = claimsJws.getBody();
        return (String) claims.get("phone");
    }

    /**
     * 移除token
     * @param token
     */
    public static void removeToken(String token) {
    }

}
